
import sys
from PySide6.QtWidgets import QApplication, QWidget, QLabel, QPushButton,QComboBox
from knserial.serial_operation import SerialOperation

class KNUIWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.serialOp = SerialOperation()
        self.show_ui()

    def show_ui(self):
        print("show window")
        self.start_posx = 50
        self.start_posy = 100

        self.serial_choose_index = 0

        self.label_serial = QLabel("串口选择 ", self)
        self.label_serial.move(self.start_posx, self.start_posy)

        self.serial_ports = self.serialOp.getPorts()

        self.serial_list = QComboBox(self)
        for port, desc, hwid in self.serial_ports:
            self.serial_list.addItem(port + " " + desc)
        self.serial_list.move(self.start_posx+80, self.start_posy)

        self.buttonSerial = QPushButton("打开串口", self)
        self.buttonSerial.move(self.start_posx, self.start_posy+ 50)
        self.buttonSerial.clicked.connect(self.on_serial_click)

        self.label = QLabel("mcu 版本号", self)
        self.label.move(self.start_posx, self.start_posy+100)  # 设置标签的位置
        self.mcu_version_str = QLabel("", self)
        self.mcu_version_str.setFixedWidth(200)
        self.mcu_version_str.move(self.start_posx+80, self.start_posy+100)


        self.button = QPushButton("获取版本号", self)
        self.button.move(self.start_posx, self.start_posy+50+100)  # 设置按钮的位置
        self.button.clicked.connect(self.on_click)  # 连接按钮点击事件


        self.serial_list.currentIndexChanged.connect(self.on_list_changed)

    def on_serial_click(self):
        if not self.serialOp.isOpen():
            ret = self.serialOp.open(self.serial_choose_index)
            if ret:
                print("open serial success")
                self.buttonSerial.setText("关闭串口")
            else:
                print("open serial fail")
                self.buttonSerial.setText("打开串口")
        else:
            self.serialOp.close()
            self.buttonSerial.setText("打开串口")

    def on_list_changed(self, index):
        self.serial_choose_index = index
        print(f"choosed: {index} {self.serial_ports[index]}")

    def on_click(self):
        # 当按钮被点击时，更新标签的文本
        self.mcu_version_str.setText("You clicked the button!")


class KNWindowDirect:
    def show_all(self):
        app = QApplication([])
        # 创建主窗口实例
        window = KNUIWindow()
        # 设置窗口标题和大小
        window.setWindowTitle("PySide6 Demo")
        window.resize(800, 600)
        # 显示窗口
        window.show()
        # 运行应用程序
        sys.exit(app.exec())
